package ece1779.ec2;

import java.io.*;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.sql.DataSource;

import org.apache.commons.fileupload.*;
import org.apache.commons.fileupload.disk.*;
import org.apache.commons.fileupload.servlet.*;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.List;


public class PreImage extends HttpServlet {
    
	public void doGet(HttpServletRequest request, HttpServletResponse response)
	throws IOException, ServletException {
		doPost(request, response);
	}
	
    public void doPost(HttpServletRequest request, HttpServletResponse response)
	throws IOException, ServletException {
        try {
        	
        	String imageId = request.getParameter("imageid");
        	response.setContentType("text/html");
        	PrintWriter out = response.getWriter();
        	
            out.write("<html><head><title>Image Sampler</title></head>");
            out.write("<body>");
            
            printImageTransformations(imageId,  out);

            out.write("</body></html>");
             
	}
	catch (Exception ex) {
	    throw new ServletException (ex);
	}
	
    }
    public void printImageTransformations(String imageId, PrintWriter out) {
    	Connection con = null;
    	try{ 
            
		    // Get DB connection from pool
		    DataSource dbcp = (DataSource)this.getServletContext().getAttribute("dbpool");
		    con = dbcp.getConnection();
	
		    // Execute SQL query
		    Statement stmt = con.createStatement();
            String    sql = "SELECT * FROM group1.images WHERE imageId =" + imageId;
            ResultSet rs =  stmt.executeQuery(sql);
            
            if (rs != null){
            	while (rs.next()){
            		String key1 = rs.getString("key1");
            		String key2 = rs.getString("key2");
            		String key3 = rs.getString("key3");
            		String key4 = rs.getString("key4");
            		out.write("<img src='http://s3.amazonaws.com/s3ece1779/" + key1 + "' />");
            		out.write("<img src='http://s3.amazonaws.com/s3ece1779/" + key2 + "' />");
            		out.write("<img src='http://s3.amazonaws.com/s3ece1779/" + key3 + "' />");
            		out.write("<img src='http://s3.amazonaws.com/s3ece1779/" + key4 + "' />");
            	}
            }
            
        }
    	catch(Exception ex) {
              getServletContext().log(ex.getMessage());  
    	}    	
    	finally {
    		try {
    		con.close();
    		}
    		catch (Exception e) {
                getServletContext().log(e.getMessage());  
    		}
    	}
 
    }   
}